import { ref } from 'vue'
import { defineStore } from 'pinia'
import type { PageConfig, StudentItem, StudentStudyListItem } from '@/config/types'
import cfg from '@/config/config'
import api from '@/api/student'
import type { StudyLogParam } from '@/config/forms'



export const useStudentStudyStore = defineStore('studentStudy', () => {
    const loading = ref<boolean>(false)
    const pager = ref<PageConfig>({
        page: 1,
        pageSize: cfg.pageLimit,
        total: 0
    })
    const search = ref<StudyLogParam>({
        accountId: 0,
        page: 1,
        limit: cfg.pageLimit
    })
    const student = ref<StudentItem | null>(null)
    const items = ref<StudentStudyListItem[]>([])

    async function loadItems(accountId: number) {
        if (accountId === search.value.accountId && 
            pager.value.page === search.value.page &&
            pager.value.pageSize == search.value.limit
        ) { //搜索条件没变化
            return
        }
        await loadStudent(accountId)
        search.value.accountId = accountId
        loading.value = true
        try {
            const res = await api.getStudyLog(search.value)
            items.value = res.data
            pager.value = {
                page: res.page,
                pageSize: res.size,
                total: res.total
            }
            loading.value = false
        } catch(e) {
            loading.value = false
        }
    }

    async function loadStudent(accountId: number) {
        if (student.value && student.value.accountId === accountId) {
            return
        }
        loading.value = true
        try {
            const res = await api.getItem(accountId)
            student.value = res.data
            loading.value = false
        } catch(e) {
            loading.value = false
        }
    }

    async function changePage(page: number, size: number) {
        search.value.page = page
        search.value.limit = size
        loadItems(search.value.accountId)
    }

    return {
        loading,
        search,
        pager,
        student,
        items,

        loadStudent,
        loadItems,
        changePage
    }
})